package kr.hkit.powerjava.chapter26.service;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.InputMismatchException;
import java.util.Scanner;

import kr.hkit.powerjava.chapter26.dao.DepartmentDAO;
import kr.hkit.powerjava.chapter26.dao.EmployeeDAO;
import kr.hkit.powerjava.chapter26.dto.Employee;

public class EmployeeService extends AbsService<Employee> {
	private ArrayList<Employee> list;
	
	public EmployeeService(Scanner sc, Connection connection) {
		super(sc, connection);
		dao = new EmployeeDAO(connection);
	}

	@Override
	public Employee inputItemInfo(boolean gubun) {
		System.out.println("사원번호 사원명");
		Employee emp = new Employee(sc.nextInt(), sc.next().trim());
		if (gubun) {
			System.out.println("직책 직속상사 월급 부서번호");
			String title = sc.next().trim();
			int manager = sc.nextInt();
			int salary = sc.nextInt();
			int dno = sc.nextInt();
			emp.setTitle(title);
			emp.setManager(manager);
			emp.setSalary(salary);
			emp.setDno(dno);
		}
		return emp;
	}

	@Override
	public void prnSubMenu() {
		System.out.print("1. 사원이름순 정렬 2. 월급순 정렬 3. 사원번호순 정렬");
		try {
			list = dao.listItems();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		int res = sc.nextInt();
		switch(res){
			case 1: //이름순
				prnItemList(new Comparator<Employee>() {
					@Override
					public int compare(Employee o1, Employee o2) {
						return o1.getEmpName().hashCode()-o2.getEmpName().hashCode();
					}
				});
				break;
			case 2: //
				prnItemList(new Comparator<Employee>() {
					@Override
					public int compare(Employee o1, Employee o2) {
						return o1.getSalary()-o2.getSalary();
					}
				});
				break;
			default:
				prnItemList(null);
		}
	}

	private void prnItemList(Comparator<Employee> comparator) {
		if (comparator == null){
			Collections.sort(list);
		}else{
			Collections.sort(list, comparator);
		}
		prnlist(list);
	}

	private void prnlist(ArrayList<Employee> list) {
		prnHead();
		for(Employee d:list){
			System.out.println(d);
		}
	}

	@Override
	public void prnHead() {
		System.out.println("*************************EMPLOYEE************************************");
		System.out.println("사원번호   사원명            직책      직속상사     월급     부서번호");
	}

	@Override
	public void prnStart() {
		System.out.println("**EMPLOYEE INFORMATION**");
	}

}
